package net.hubt.itc.util;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;



import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import org.w3c.dom.Element;


public class XMLDocument {
	public static final String TAG = XMLDocument.class.getSimpleName();
	public static final String UTF8_BOM = "\uFEFF";
	public String getXmlTextDataFromUrl(String url) {
		String xml = null;

		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			xml = EntityUtils.toString(httpEntity, "UTF-8");			
		} catch (UnsupportedEncodingException e) {			
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//remove BOM character
		if(xml!=null){
			if(xml.startsWith(UTF8_BOM)) return xml.substring(1);
		}
		return xml;
	}

	public Document getDocument(String xml) {
		if(xml!=null){
			StringBuffer sbXml=new StringBuffer(xml);		
			//remove BOM character
			if(xml.startsWith(UTF8_BOM)) sbXml.deleteCharAt(0);
			Document doc = null;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			try {
				DocumentBuilder db = dbf.newDocumentBuilder();
				InputSource is = new InputSource();
				//is.setEncoding("UTF-8");
				is.setCharacterStream(new StringReader(sbXml.toString()));
				doc = db.parse(is);
			} catch (ParserConfigurationException ex) {
				
				return null;
			} catch (SAXException ex) {
				
				return null;
			} catch (IOException ex) {
				
				return null;
			}
			return doc;
		}
		return null;
	}
	
//	public Element getRootNode(Document doc){
//		return doc.getDocumentElement();
//	}
	
	/**
	 * parse and get root document element from xml text data
	 * @param xml text data 
	 * @return root document node
	 */
	public Element getRootNode(String xml){
		return getDocument(xml).getDocumentElement();
	}
}
